<?php

/**
 * File Description
 * 
 * Kao: PHP Web Framework <http://kao.byhuy.com/>.
 * Copyright 2008, Huy Nguyen <http://www.byhuy.com/>.
 * 
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 * 
 */

require_once 'Kao/Router/Abstract.php';

class Kao_Router_Php extends Kao_Router_Abstract
{
    
    protected $_routes = array();
    
    /**
     * Sets routes
     * 
     * @return Kao_Router_Php
     */
    public function setRoutes($routes)
    {
        $this->_routes = $routes;
        return $this;
    }
    
    /**
     * Routes
     */
    public function route()
    {
        $requestUrl = $this->getRequestUrl();
        
        $matches = array();
        
        foreach ($this->_routes as $url => $info)
        {
            if (preg_match_all('/' . addslashes($url) .'/', $requestUrl, $matches, PREG_SET_ORDER))
            {
                array_shift($matches[0]);
                // TODO How about numbered parameters if we need only named parameters ?
                $matches = $matches[0];
                
                // require Request class
                // TODO what if the user want to use another request class ?
                require_once 'Kao/Request.php';
                
                $httpMethod = $this->getHttpMethod();
                $request = new Kao_Request($requestUrl, $info['controller'], $httpMethod, $matches);
                return $request;
            }
        }
    }
    
    /**
     * Returns HTTP METHOD name.
     */
    public function getHttpMethod()
    {
        $requestMethod = $_REQUEST['REQUEST_METHOD'];
        
        // if request method is POST, check if there's a method override?
        if ($requestMethod == 'POST')
        {
            if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']) && !empty($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) 
            {
                $tempMethod = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
            }
            elseif (isset($_REQUEST['__http_method_override']) && !empty($_REQUEST['__http_method_override']))
            {
                $tempMethod = $_REQUEST['__http_method_override'];
            }
            
            $allowedMethods = array('GET' => 0, 'POST' => 0, 'PUT' => 0, 'DELETE' => 0, 'HEAD' => 0);
            if (isset($allowedMethods[$tempMethod]))
            {
                $requestMethod = $tempMethod;
            }
        }
               
        return $requestMethod;
    }
}

